<template>
  <div class="gi_table_page">
    <GiTable title="设备清单" row-key="id" :data="dataList" :columns="columns" :loading="loading"
      :scroll="{ x: '100%', y: '100%', minWidth: 1000 }" :pagination="pagination" :disabled-tools="['size']"
      :disabled-column-keys="['name']" @refresh="search">

      <template #toolbar-left>
        <a-input :style="{width:'320px'}" v-model="queryForm.fuzzy" placeholder="编号/类型/品牌/型号" allow-clear
          @change="search">
          <template #prefix><icon-search /></template>
        </a-input>

        <a-select :style="{width:'100px'}" v-model="queryForm.status" placeholder="状态" allow-clear @change="search">
          <a-option value="1">闲置</a-option>
          <a-option value="2">使用中</a-option>
          <a-option value="3">借用中</a-option>
          <a-option value="4">维修中</a-option>
          <a-option value="5">已报废</a-option>
        </a-select>

        <a-button @click="reset">
          <template #icon><icon-refresh /></template>
          <template #default>重置</template>
        </a-button>

      </template>
      <template #toolbar-right>
        <a-button v-permission="['asset:device:records:create']" type="primary" @click="onAdd">
          <template #icon><icon-plus /></template>
          <template #default>新增</template>
        </a-button>
        <a-button v-permission="['asset:device:records:print']" type="dashed" @click="onAdd">
          <template #icon><icon-tag /></template>
          <template #default>打印标签</template>
        </a-button>
        <a-button v-permission="['asset:device:records:recycle']" type="dashed" status="danger" @click="onRecycle">
          <template #icon><icon-delete /></template>
          <template #default>回收站</template>
        </a-button>
        <a-button v-permission="['asset:device:records:import']" type="primary" status="success" @click="onAdd">
          <template #icon><icon-import /></template>
          <template #default>导入设备</template>
        </a-button>
        <a-button v-permission="['asset:device:records:export']" @click="onExport">
          <template #icon><icon-download /></template>
          <template #default>导出</template>
        </a-button>
      </template>

      <template #status="{ record }">
        <a-tag v-if="record.status === 1" color="purple" size="small">闲置</a-tag>
        <a-tag v-if="record.status === 2" color="green" size="small">使用中</a-tag>
        <a-tag v-if="record.status === 3" color="arcoblue" size="small">借用中</a-tag>
        <a-tag v-if="record.status === 4" color="orange" size="small">维修中</a-tag>
        <a-tag v-if="record.status === 5" color="grey" size="small">已报废</a-tag>
      </template>
      <template #userNickname="{ record }">
        <a-link v-if="record.status === 3">
          <span style="color:red">[借用]</span>
        </a-link>
          {{ record.userNickname }}
      </template>

      <template #action="{ record }">
        <a-space>
          <a-link v-permission="['asset:device:records:archive']" title="设备档案" @click="onDetail(record)">
            <template #icon>
              <icon-eye />
            </template>
            设备档案</a-link>
          <a-link v-if=" record.isDel == 0" v-permission="['asset:device:records:update']" title="修改"
            @click="onUpdate(record)">
            <template #icon>
              <icon-edit />
            </template>
            修改</a-link>
          <a-link v-if=" record.isDel == 1" v-permission="['asset:device:records:delete:return']" title="撤销删除"
            @click="onDeleteReturn(record)">
            <template #icon>
              <icon-edit />
            </template>
            撤销删除</a-link>

          <a-dropdown v-if=" record.isDel == 0">
            <a-button v-if="has.hasPermOr(['asset:device:records:delete', 'asset:device:records:update'])" type="text"
              size="mini" title="更多">
              <template #icon>
                <icon-more :size="16" />
              </template>
            </a-button>
            <template #content>
              <a-doption v-permission="['asset:device:records:delete']" v-if="record.status != 5 && record.isDel !=1"
                title="删除" @click="onDelete(record)">删除</a-doption>
              <a-doption v-permission="['asset:device:records:use']"
                v-if="record.status != 5 && record.status !=3 && record.isDel !=1" title="分配用户"
                @click="onUse(record)">分配</a-doption>
              <a-doption v-permission="['asset:device:records:lend']"
                v-if="record.status != 5 && record.status !=3 && record.status !=2 && record.isDel !=1" title="借用"
                @click="onLend(record)">借用</a-doption>
              <a-doption v-permission="['asset:device:records:return']" v-if="record.status === 3 && record.isDel !=1"
                title="归还" @click="onReturn(record)">归还</a-doption>
              <a-doption v-permission="['asset:device:records:discard']" v-if="record.status != 5 && record.isDel !=1"
                title="报废" @click="onDiscard(record)">报废</a-doption>
              <a-doption v-permission="['asset:device:records:undiscard']"
                v-if="record.status === 5 && record.isDel !=1" title="撤销报废"
                @click="onDiscardCancel(record)">撤销报废</a-doption>
              <a-doption v-permission="['asset:device:records:updateRole']"
                v-if="record.status != 5 && record.isDel !=1" title="故障报修" @click="onDelete(record)">故障报修</a-doption>
            </template>
          </a-dropdown>
        </a-space>
      </template>
    </GiTable>

    <DeviceRecordsAddDrawer ref="DeviceRecordsAddDrawerRef" @save-success="search" />
    <DeviceRecordsDetailDrawer ref="DeviceRecordsDetailDrawerRef" />
    <DeviceUseModal ref="DeviceUseModalRef" @save-success="search" />
    <DeviceLendModal ref="DeviceLendModalRef" @save-success="search" />
    <DeviceReturnModal ref="DeviceReturnModalRef" @save-success="search" />
    <DeviceDiscardModal ref="DeviceDiscardModalRef" @save-success="search" />
    <DeviceDiscardCancelModal ref="DeviceDiscardCancelModalRef" @save-success="search" />

  </div>
</template>

<script setup lang="ts">
  import DeviceRecordsAddDrawer from './DeviceRecordsAddDrawer.vue'
  import DeviceRecordsDetailDrawer from './DeviceRecordsDetailDrawer.vue'
  import DeviceUseModal from './DeviceUseModal.vue'
  import DeviceLendModal from './DeviceLendModal.vue'
  import DeviceReturnModal from './DeviceReturnModal.vue'
  import DeviceDiscardModal from './DeviceDiscardModal.vue'
  import DeviceDiscardCancelModal from './DeviceDiscardCancelModal.vue'

  import { type DeviceRecordsResp, type DeviceRecordsQuery, deleteDeviceRecords, deleteReturnDeviceRecords, exportDeviceRecords, listDeviceRecords } from '@/apis/asset/device/records'
  import type { TableInstanceColumns } from '@/components/GiTable/type'
  import type { ColumnItem } from '@/components/GiForm'

  import { useDownload, useTable } from '@/hooks'
  import { useDict } from '@/hooks/app'
  import { isMobile } from '@/utils'
  import has from '@/utils/has'

  defineOptions({ name: 'DeviceRecords' })

  const queryForm = reactive < DeviceRecordsQuery > ({
    fuzzy: undefined,
    isDel: 0,
    status: undefined,
    sort: ['id,desc']
  })

  const {
    tableData: dataList,
    loading,
    pagination,
    search,
    handleDelete
  } = useTable((page) => listDeviceRecords({ ...queryForm, ...page }), { immediate: true })
  const columns = ref < TableInstanceColumns[] > ([

    { title: '设备编号', dataIndex: 'code', slotName: 'code' },
    { title: '二维码', dataIndex: 'qrCodeUrl', slotName: 'qrCodeUrl', show: false },
    { title: '使用人', dataIndex: 'userNickname', slotName: 'userNickname' },
    { title: '分类', dataIndex: 'categoryName', slotName: 'categoryName' },
    { title: '名称', dataIndex: 'name', slotName: 'name', show: false },
    { title: '品牌', dataIndex: 'brand', slotName: 'brand' },
    { title: '型号', dataIndex: 'model', slotName: 'model' },
    { title: '所属机构', dataIndex: 'deptName', slotName: 'deptName', show: false },
    { title: '状态', dataIndex: 'status', slotName: 'status' },
    { title: '登记日期', dataIndex: 'purchaseDate', slotName: 'purchaseDate' },
    { title: '到期日期', dataIndex: 'expireDate', slotName: 'expireDate' },
    { title: '折旧规则ID', dataIndex: 'depreciationRuleId', slotName: 'depreciationRuleId', show: false },
    { title: '序列号', dataIndex: 'sn', slotName: 'sn', show: false },
    { title: '供应商', dataIndex: 'producerName', slotName: 'producerName' },
    { title: '采购价格', dataIndex: 'price', slotName: 'price', show: false },
    { title: '描述', dataIndex: 'description', slotName: 'description', show: false },
    {
      title: '操作',
      dataIndex: 'action',
      slotName: 'action',
      width: 250,
      align: 'center',
      fixed: !isMobile() ? 'right' : undefined,
      show: has.hasPermOr(['asset:device:records:detail', 'asset:device:records:update', 'asset:device:records:delete'])
    }
  ]);

  // 重置
  const reset = () => {
    queryForm.fuzzy = undefined
    queryForm.status = undefined
    queryForm.isDel = 0
    search()
  }

  // 删除
  const onDelete = (record: DeviceRecordsResp) => {
    return handleDelete(() => deleteDeviceRecords(record.id), {
      content: `是否确定删除该条数据？`,
      showModal: true
    })
  }

  // 撤销删除
  const onDeleteReturn = (record: DeviceRecordsResp) => {
    console.log(record.id)
    return handleDelete(() => deleteReturnDeviceRecords(record.id), {
      content: `是否撤销删除该条数据？`,
      showModal: true
    })
  }

  // 导出
  const onExport = () => {
    useDownload(() => exportDeviceRecords(queryForm))
  }

  const DeviceRecordsAddDrawerRef = ref < InstanceType < typeof DeviceRecordsAddDrawer >> ()
  // 新增
  const onAdd = () => {
    DeviceRecordsAddDrawerRef.value?.onAdd()
  }

  // 修改
  const onUpdate = (record: DeviceRecordsResp) => {
    DeviceRecordsAddDrawerRef.value?.onUpdate(record.id)
  }

  // 回收站
  const onRecycle = () => {
    queryForm.isDel = 1
    search()
  }

  const DeviceRecordsDetailDrawerRef = ref < InstanceType < typeof DeviceRecordsDetailDrawer >> ()
  // 设备档案
  const onDetail = (record: DeviceRecordsResp) => {
    DeviceRecordsDetailDrawerRef.value?.onOpen(record.id)
  }

  const DeviceUseModalRef = ref < InstanceType < typeof DeviceUseModal >> ()
  // 分配用户
  const onUse = (record: DeviceRecordsResp) => {
    DeviceUseModalRef.value?.onOpen(record.id)
  }

  const DeviceLendModalRef = ref < InstanceType < typeof DeviceLendModal >> ()
  // 借用
  const onLend = (record: DeviceRecordsResp) => {
    DeviceLendModalRef.value?.onOpen(record.id)
  }

  const DeviceReturnModalRef = ref < InstanceType < typeof DeviceReturnModal >> ()
  // 归还
  const onReturn = (record: DeviceRecordsResp) => {
    DeviceReturnModalRef.value?.onOpen(record.id, record.userId)
  }

  const DeviceDiscardModalRef = ref < InstanceType < typeof DeviceDiscardModal >> ()
  // 报废
  const onDiscard = (record: DeviceRecordsResp) => {
    DeviceDiscardModalRef.value?.onOpen(record.id, record.userId)
  }

  const DeviceDiscardCancelModalRef = ref < InstanceType < typeof DeviceDiscardCancelModal >> ()
  // 撤销报废
  const onDiscardCancel = (record: DeviceRecordsResp) => {
    DeviceDiscardCancelModalRef.value?.onOpen(record.id, record.userId)
  }

</script>

<style scoped lang="scss"></style>